package com.market.cash.ui.presenter

import com.market.cash.analyse.util.GoogleUtil
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.view.ICashRootLoginView
import com.market.cash.utils.CashRootDateUtil
import com.market.cash.utils.helper.CashRootAnalysisHelper
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.utils.helper.TestAnalysisAddEvent
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/17 11:59
 * @Annotation：登录
 */
class CashRootLoginPresenter(private val iView: ICashRootLoginView): ProPresenter(iView) {

    /**
     * 登录
     */
    fun requestLoginAction(){
        //登录之前，需要验证手机号是否在 app配置 accList里存在
        val accItem = checkCashRootConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_IS_CONFIG_ACCOUNT,true)
            onLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_LOGIN_URL)
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ApiService.API_PATH.CASHROOT_API_LOGIN_NO_CODE_PATH)
                put("mobile",iView.getMobile())//手机号
                put("code","0000")//验证码
                put("channelCode", GoogleUtil.getInstallReferrer())//渠道号
                put("subChannelCode", GoogleUtil.getInstallReferrer())//子渠道号
                put("directLoginFlag","YES")//是否直接登录
                put("notBindWalletFlag","YES")//不自动绑卡
                put("loginParam","")//验证码接口返回的参数
            }

        doCashRootPostAction(httpUrl, params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_IS_ADSOURCE,true)
                    }

                    //登录类型 == 注册，需要打点
                    if (type == "REGISTER"){
                        TestAnalysisAddEvent.addRegisterEvent()
                    }
                    onLoginSuccess(userId,userToken)
                }
            }

            override fun onRequestError(error: JSONObject) {
                iView.showLoginFailure(error)
            }

            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkCashRootConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val customize = CashRootCustomConfigsHelper.getCashRootConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (iView.getMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录成功
     */
    private fun onLoginSuccess(uid: String, token: String){
        iView.hideCashRootLoading()
        //保存手机号码，个人中心使用
        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_MOBILE, iView.getMobile())
        //保存用户登录时间
        val loginTime = CashRootDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_LOGIN,true)
        //保存用户id
        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_USERID,uid)
        //保存用户Token
        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        CashRootAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        iView.showMainPage()
    }
}